// pages/detail-song/detail-song.js
import rankingStore from "../../store/rankingStore"
import playerStore from '../../store/playerStore'
import { getPlaylistDetail } from "../../services/modules/music"

Page({

  data: {
    type: "ranking",
    key: "newRanking",
    id: "",
    songInfo: {}
  },

  // 歌曲点击，更改播放列表
  songHandle(){
    playerStore.dispatch('setPlayListSongs',this.data.songInfo.tracks)
  },


  onLoad(options) {
    // 1.确定获取数据的类型
    // type: ranking -> 榜单数据
    // type: menu -> 热门和推荐

    const type = options.type
    this.setData({ type })

    // ranking要去store拿数据，menu记录id用来拿数据
    if (type === "ranking") {
      const key = options.key
      this.data.key = key
      rankingStore.onState(key, this.handleRanking)
    } else if (type === "menu") {
      const id = options.id
      this.data.id = id
      this.fetchMenuSongInfo()
    }
  },

  // 通过id获取具体的歌曲列表
  async fetchMenuSongInfo() {
    const res = await getPlaylistDetail(this.data.id)
    this.setData({ songInfo: res.playlist })
  },

  // 监听store获取歌曲列表
  handleRanking(value) {
    this.setData({ songInfo: value })
    wx.setNavigationBarTitle({
      title: value.name,
    })
  },

  onUnload() {
    if (this.data.type === "ranking") {
      rankingStore.offState(this.data.key, this.handleRanking)
    }
  }
})